const { aliyunOSS } = require('../config.js');
const Base64 = require('./Base64.js');
console.log();
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');

const uploadFile = (params) => {
    if (!params.filePath || params.filePath.length < 9) {
        wx.showModal({
            title: '图片错误',
            content: '请重试',
            showCancel: false,
        })
        return;
    }
    wx.showToast({
        title: '上传成功！'
    })
    console.log(params);
    const aliyunFileKey = fileName(params.dir,params.filePath,params.fileName);
 
    console.log(aliyunFileKey)
    const aliyunServerURL = aliyunOSS.uploadImageUrl;
    const accessid = aliyunOSS.OSSAccessKeyId;
    const policyBase64 = getPolicyBase64();
    const bucket = aliyunOSS.AliOSSBucketName;
    const signature = getSignature(policyBase64);

    wx.uploadFile({
        url: aliyunServerURL,
        filePath: params.filePath,
        name: 'file',
        formData: {
            'key': aliyunFileKey,
            'policy': policyBase64,
            'OSSAccessKeyId': accessid,
            'signature': signature,
            'bucket': bucket,
            'success_action_status': '200',
        },
        success(res) {
            if (res.statusCode != 200) {
                if (params.fail) {
                    params.fail(res)
                }
                return;
            }
            if (params.success) {
                params.success(aliyunFileKey);
            }
        },
        fail(err) {
            err.wxaddinfo = aliyunServerURL;
            if (params.fail) {
                params.fail(err)
            }
        },
        complete() {
            if (params.complete){
                params.complete();
            }
        }
    })
}

const fileName = (dir,filePath,file_name) => {
    const prefix = 'm';
    let timeStamp = Date.parse(new Date());
    const arr = [0,1,2,3,4,5,6,7,8,9];
    let str = '';
    for(let i = 0; i < 4; i++){
        let pos = Math.round(Math.random() * (arr.length - 1));
        str += arr[pos];
    } 
    var temp = filePath.split(".");
    var ext = temp[temp.length-1];
    if (filePath.indexOf('aac')!='-1')
    { 
      return `${dir}/${prefix}${timeStamp}${str}.aac`;
    }
    if (filePath.indexOf('pdf')!='-1')
    { 
      return `${dir}/${file_name}_${str}.pdf`;
    }
    
    return `${dir}/${prefix}${timeStamp}${str}.${ext}`;
}

const getPolicyBase64 = () => {
    let date = new Date();
    date.setHours(date.getHours() + aliyunOSS.timeout);
    let srcT = date.toISOString();
    const policyText = {
        "expiration": srcT, //设置该Policy的失效时间
        "conditions": [
            ["content-length-range", 0, 50 * 1024 * 1024] // 设置上传文件的大小限制,5mb
        ]
    };
    const policyBase64 = Base64.encode(JSON.stringify(policyText));
    return policyBase64;
}

const getSignature = (policyBase64) => {
    const accesskey = aliyunOSS.AccessKeySecret;
    const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
        asBytes: true
    });
    const signature = Crypto.util.bytesToBase64(bytes);
    return signature;
}

module.exports = uploadFile;